#include "arcsegment.h"
#include <QPainterPath>
#include <QtMath>

ArcSegment::ArcSegment(QGraphicsItem* parent)
    : TrackSegment(Arc, parent)
    , m_center(250, 0)
    , m_radius(250.0)
    , m_startAngle(0.0)
    , m_spanAngle(180.0)
{
    updatePath();
}

double ArcSegment::length() const
{
    return qAbs(m_spanAngle) * M_PI / 180.0 * m_radius;
}

QPointF ArcSegment::getPointAt(double distance) const
{
    if (length() <= 0) return m_center + QPointF(m_radius, 0);
    
    double t = qBound(0.0, distance / length(), 1.0);
    double angle = m_startAngle + t * m_spanAngle;
    double rad = angle * M_PI / 180.0;
    
    return m_center + QPointF(m_radius * cos(rad), m_radius * sin(rad));
}

double ArcSegment::getAngleAt(double distance) const
{
    Q_UNUSED(distance)
    if (length() <= 0) return 0.0;
    
    double t = qBound(0.0, distance / length(), 1.0);
    double angle = m_startAngle + t * m_spanAngle;
    
    return angle * M_PI / 180.0;
}

void ArcSegment::updatePath()
{
    QPainterPath path;
    path.arcMoveTo(QRectF(m_center.x() - m_radius, m_center.y() - m_radius,
                           m_radius * 2, m_radius * 2), m_startAngle);
    path.arcTo(QRectF(m_center.x() - m_radius, m_center.y() - m_radius,
                      m_radius * 2, m_radius * 2), m_startAngle, m_spanAngle);
    
    setPath(path);
    setPen(QPen(color(), trackWidth()));
}

void ArcSegment::setRadius(double radius)
{
    m_radius = qMax(10.0, radius);
    updatePath();
}

void ArcSegment::setAngle(double angle)
{
    m_spanAngle = angle;
    updatePath();
}

void ArcSegment::setCenter(qreal x, qreal y)
{
    QPointF f(x,y);
    setCenter(f);
}

void ArcSegment::setCenter(const QPointF& center)
{
    m_center = center;
    updatePath();
}

void ArcSegment::setStartAngle(double angle)
{
    m_startAngle = angle;
    updatePath();
}

void ArcSegment::setSpanAngle(double angle)
{
    m_spanAngle = angle;
    updatePath();
}
